/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */

package org.osami.gateway.storage.naive.internal;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Property;
import org.apache.felix.ipojo.annotations.Provides;
import org.osami.gateway.sensor.SenseData;
import org.osami.gateway.storage.ISenseDataStorage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

@Component
@Provides
@Instantiate
public class NaiveSenseDataStorage implements ISenseDataStorage {

    /**
     * Period size in seconds.
     */
    @Property(name = "period.size", value = "60")
    private long periodSize;

    @Property(name = "senses.max", value = "1000")
    private int maxSenseData;

    private Set<SenseData> datas;

    public NaiveSenseDataStorage() {
        this(20, 200);
    }

    public NaiveSenseDataStorage(long periodSize, int maxSenseData) {
        this.periodSize = periodSize;
        this.maxSenseData = maxSenseData;
        this.datas = Collections.synchronizedSet(new TreeSet<SenseData>(new TimestampComparator()));
    }

    public void store(SenseData data) {
        synchronized(this) {
            reduce();
            datas.add(data);
        }
    }

    private void reduce() {
        if (datas.size() > maxSenseData) {
            // Too much datas, remove the older one (the first)
            Iterator<SenseData> i = iteratorInternal();
            i.next();
            i.remove();
        }

        long current = System.currentTimeMillis();
        long limitTimestamp = current - (periodSize * 1000);

        // Kind of ugly, but it works ;)
        // I just want to remove the first entry if it is too old.
        // As soon as there are no more entries to cleanup, we stop
        while (cleanFirstEntry(limitTimestamp));
    }

    private boolean cleanFirstEntry(long limitTimestamp) {
        // Important: do not use directly iterator here, that should cause infinite loop !!!
        Iterator<SenseData> i = iteratorInternal();
        SenseData sense = null;
        if (i.hasNext()) {
            sense = i.next();
            if (sense.getTimeStamp() < limitTimestamp) {
                i.remove();
                return true;
            }
        }
        return false;
    }

    public void cleanup() {
        synchronized (this) {
            datas.clear();
        }
    }

    public Iterator<SenseData> iterator() {
        synchronized (this) {
            reduce();
            return iteratorInternal();
        }
    }

    private Iterator<SenseData> iteratorInternal() {
        return datas.iterator();
    }

}
